package card_game;

import java.util.List;

public class Deck<T extends Card> {
    private List<T> cards;
    private int dealtIndex;

    public Deck() {
	//cards = new ArrayList<T>();
	dealtIndex = 0;
    }

    public void setDeckOfCards(List<T> deckOfCards) {
	cards = deckOfCards;
    }

    public void shuffle() {
	int size = cards.size();
	for (int i = 0; i < size; i++) {
	    int j = (int)(Math.random() * (size - i)) + i;
	    if (i != j) {
		T card1 = cards.get(i);
		T card2 = cards.get(j);
		cards.set(i, card2);
		cards.set(j, card1);
	    }
	}
    }

    public int remainingCards() {
	return cards.size() - dealtIndex;
    }

    public T[] dealHand(int number) {
	if (remainingCards() < number)
	    return null;
	
	@SuppressWarnings("unchecked")
	T[] hand = (T[]) new Card[number];
			/**
			 * GQ.
			 * Cannot make a generic array.
			 */
//	    new T[number];
	int count = 0;
	while (count < number) {
	    T card = dealCard();
	    if (card != null) {
		hand[count] = card;
		count++;
	    }
	}
	return hand;
    }

    public T dealCard() {
	if (remainingCards() == 0) {
	    return null;
	}
	
	T card = cards.get(dealtIndex);
	card.makeUnavailable();
	dealtIndex++;

	return card;
    }
    
    public void resetDeck() {
    	dealtIndex = 0;
    	shuffle();
    }

    public void print() {
	for (Card card : cards) {
	    card.print();
	}
    }
}